<template>
  <div class="app-container">
    <u-page v-if="!scheduleChoosed.id" title="返券操作">
      <div slot="header">
        <el-button icon="el-icon-search" type="primary" @click="dialogFormVisible=true">选择档期活动主题</el-button>
      </div>
    </u-page>
    <!--  选择档期主题   -->
    <u-dialog title="选择档期活动主题" :show.sync="dialogFormVisible" width="700px" @confirm="chooseSchedule">
      <el-form>
        <el-form-item label="档期主题" prop="scheduleId">
          <Schedule v-model="schedule" type-id="1" valid="valid" width="500px" @change="changeScheduleQuery" />
        </el-form-item>
      </el-form>
    </u-dialog>

    <!--  返券页面  -->
    <div v-if="scheduleChoosed.id">
      <u-page :title="scheduleChoosed.id === ''? '返券操作':scheduleChoosed.name">
        <div slot="header">
          <el-button icon="el-icon-search" type="primary" @click="dialogFormVisible=true">选择档期活动主题</el-button>
        </div>
        <u-filtered>
          <el-form :inline="true" class="search-form">
            <el-form-item label="会员卡号" prop="card_no">
              <el-input v-model="card_no" clearable placeholder="输入会员卡号" style="width: 170px" />
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="queryOrder()">查询可返券订单</el-button>
            </el-form-item>
            <el-form-item label="订单号" prop="saleNo">
              <el-input ref="inputRef" v-model="saleNo" clearable placeholder="输入订单号回车添加" style="width: 170px" @keyup.enter.native="addOrder()" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="clear()">清空订单</el-button>
            </el-form-item>
          </el-form>
        </u-filtered>
      </u-page>
      <div class="operation">
        <div v-for="(item,index) in dataList" :key="index" class="operation-item">
          <div class="operationitem-name">{{ item.rebateOperation.name }}</div>
          <div>
            <div class="operationitem-order">
              <el-checkbox-group v-for="(order,oIndex) in item.orderList" :key="oIndex" v-model="item.checkedArr" :disabled="ifcheckbox" @change="handleCheckedOrderChange($event,index,oIndex)">
                <el-checkbox :label="order" class="order-item">
                  <div>
                    <div>订单号：{{ order.saleNo }}</div>
                    <div>订单金额：{{ order.saleAmount }}</div>
                    <div>有效金额：{{ order.validAmount }}</div>
                  </div>
                </el-checkbox>
              </el-checkbox-group>
              <el-checkbox v-model="item.selected" :disabled="ifcheckbox" @change="handleCheckAllChange($event,index)"><span style="color:green;font-weight: bold">全选</span></el-checkbox>
            </div>
          </div>
          <div style="background-color: #5E8E3D;color:#fff;padding:10px;">
            <div>有效金额：<span class="">{{ totalPrice(index) }}</span></div>
            <div>补足金额：<span class="">{{ calDifference(index)==dataList[index].rebateOperation.threshold? 0:calDifference(index) }}</span></div>
            <div>返券金额：<span style="color: orange;">{{ totalBenifit(index) }}</span></div>
          </div>
        </div>
      </div>
      <div class="div-bottom">
        <div style="border-bottom: 1px solid #E4E6E9;padding-bottom: 10px;">总计返券金额：<span class="colorR">{{ totalRebate() }}</span></div>
        <div style="padding-top:10px;">
          <el-form :inline="true">
            <el-form-item>
              <el-button type="primary" :disabled="btnSub" @click="qr">提交小票</el-button>
              <el-button type="primary" :disabled="btnRebate" @click="getToken">返券</el-button>
              <el-button type="primary" :disabled="btnCancel" @click="cancelRebate">撤销</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-if="qrCodeVisible" style="position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(0,0,0,0.3);z-index: 9999">
        <div style="padding:20px;width:300px;height:340px;background-color: #fff;margin: 0 auto; margin-top:150px;">
          <div style="text-align: center;margin-bottom:20px;"><span style="font-size:18px;">扫码领券</span></div>
          <!-- 二维码图片 -->
          <div id="qrCodeUrl" />
          <div style="text-align: center;margin-top:20px;"><span style="font-size:18px;">二维码有效时间：{{ second }}秒</span></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import Schedule from '../../components/schedule'
let chooseList = []
export default {
  components: {
    Schedule
  },
  data() {
    return {
      api: this.$u.api.RebatenewRebatecoupon,
      dialogFormVisible: true, // 选择主题弹框
      schedule: {},
      scheduleChoosed: {}, // 选择的档期主题
      ifcheckbox: false, //  复选框可选状态
      btnSub: false,
      btnRebate: true,
      btnCancel: true,
      custno: '', // 提交小票后返回的custno
      second: 20,
      qrCodeVisible: false, // 二维码弹框
      listLoading: false,
      card_no: '', // 通过会员卡号查询小票
      saleNo: '', // 添加小票号
      openid: '',
      checkAll: false,
      checkedArr: [], // 复选框选中的值
      isCheckAll: false, // 是否全选,
      rebateAmount: 0,
      // 可返券订单
      dataList: [],
      rules: {
        scheduleId: [
          { required: true, message: '请选择档期主题', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    changeScheduleQuery(item) {
      this.schedule = item
    },
    // 选择主题
    chooseSchedule() {
      console.log(typeof (this.schedule))
      if (this.schedule.id === '' || typeof (this.schedule.id) === 'undefined') {
        alert('请选择档期主题')
      } else {
        this.dialogFormVisible = false
        this.scheduleChoosed = this.schedule
        setTimeout(() => {
          this.$refs.inputRef.focus()
        }, 0)
      }
    },
    // 二维码倒计时
    countdown() {
      this.second = 20
      var countDown = setInterval(() => {
        if (this.second < 1) {
          this.second = 20
          this.qrCodeVisible = false
          clearInterval(countDown)
        } else if (this.second >= 0) {
          this.second--
        }
      }, 1000)
    },
    // 查询会员可返券订单
    queryOrder() {
      this.dataList = []
      const card_no = this.card_no
      if (card_no === '') {
        return
      }
      this.listLoading = true
      this.api.getorderbycard({
        'card_no': card_no,
        'scheduleId': this.scheduleChoosed.id
      }).then(res => {
        // 获取列表数据
        const dataList = res.data
        if (dataList.length === 0) {
          this.$message.error('无可返券订单')
        } else {
          for (let i = 0; i < dataList.length; i++) {
            dataList[i]['checkedArr'] = []
          }
          this.dataList = dataList
        }
        console.log(res)
        // 关闭加载状态
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 全选
    handleCheckAllChange(val, index) {
      // console.log(val)
      const dataList = this.dataList
      dataList[index].selected = val
      for (let i = 0; i < dataList[index].orderList.length; i++) {
        dataList[index].orderList[i].selected = val
      }
      dataList[index].checkedArr = val ? this.dataList[index].orderList : []
    },
    // 选择订单
    handleCheckedOrderChange(value, index, oIndex) {
      const orderList = this.dataList[index].orderList
      orderList[oIndex].selected = !orderList[oIndex].selected
      const checkedCount = value.length
      this.dataList[index].selected = checkedCount === orderList.length
      // console.log(this.dataList)
    },
    // 计算单个活动总有效金额
    totalPrice(index) {
      const dataList = this.dataList
      let total = 0
      for (let j = 0; j < dataList[index].orderList.length; j++) {
        if (dataList[index].orderList[j].selected) {
          total += dataList[index].orderList[j].validAmount
        }
      }
      return total
    },
    // 计算单个活动总返券金额
    totalBenifit(index) {
      const amount = this.totalPrice(index)
      const threshold = this.dataList[index].rebateOperation.threshold
      const giftValue = this.dataList[index].rebateOperation.giftValue
      return parseInt(amount / threshold) * giftValue
    },
    // 计算单个活动补足金额
    calDifference(index) {
      const amount = this.totalPrice(index)
      const threshold = this.dataList[index].rebateOperation.threshold
      return threshold - amount % threshold
    },
    // 计算总返券金额
    totalRebate() {
      const dataList = this.dataList
      let total = 0
      for (let i = 0; i < dataList.length; i++) {
        total += this.totalBenifit(i)
      }
      return total
    },
    // 添加小票
    addOrder() {
      const saleNo = this.saleNo
      console.log(saleNo)
      if (saleNo === '') {
        return
      }
      this.api.getorderbysaleno({
        'saleNo': saleNo,
        'scheduleId': this.scheduleChoosed.id
      }).then(res => {
        console.log(res)
        if (res.data.flag === 0) {
          const item = res.data
          item['checkedArr'] = []
          console.log(item)
          // 判断及添加操作
          const dataList = this.dataList
          // 如果已有其他订单数据
          if (dataList.length > 0) {
            let index = -1
            for (let i = 0; i < dataList.length; i++) {
              if (item.rebateOperation.id === dataList[i].rebateOperation.id) {
                index = i
                break
              }
            }
            if (index >= 0) {
              let flag = true
              const orderList = dataList[index].orderList
              for (let i = 0; i < orderList.length; i++) {
                if (item.orderList[0].saleNo === orderList[i].saleNo) {
                  flag = false
                  break
                }
              }
              if (flag) {
                orderList.push(item.orderList[0])
                this.$u.msg('添加成功！')
              } else {
                this.$message.error('该小票已存在')
              }
            } else {
              dataList.push(item)
            }
            // this.dataList.
          } else {
            dataList.push(item)
            // console.log('datalist', this.dataList)
          }
        } else {
          this.$message.error('该小票无可用规则或已返券')
        }
      })
      this.saleNo = ''
      this.listLoading = false
      setTimeout(() => {
        this.$refs.inputRef.focus()
      }, 0)
    },
    // 提交-相关判定
    qr() {
      const dataList = this.dataList
      let ifright = true
      const rebateAmount = this.totalRebate()
      for (let i = 0; i < dataList.length; i++) {
        let ifchoose = false
        for (let j = 0; j < dataList[i].orderList.length; j++) {
          if (dataList[i].orderList[j].selected) {
            ifchoose = true
            break
          }
        }
        if (ifchoose && this.totalBenifit(i) === 0) {
          ifright = false
        }
      }
      if (ifright && rebateAmount > 0) {
        this.saveOrder()
      } else {
        this.$message.error('尚未选择订单或存在已选择订单但返券金额为0的活动档期，请重新确认!')
      }
    },
    // 先存小票
    saveOrder() {
      this.ifcheckbox = true
      chooseList = []
      // 获取选中的数
      const dataList = this.dataList
      for (let i = 0; i < dataList.length; i++) {
        const chooseOrderList = []
        for (let j = 0; j < dataList[i].orderList.length; j++) {
          if (dataList[i].orderList[j].selected) {
            chooseOrderList.push(dataList[i].orderList[j])
          }
        }
        if (chooseOrderList.length > 0) {
          const obj = {}
          obj['amount'] = this.totalBenifit(i)
          obj['rebateOperation'] = dataList[i].rebateOperation
          obj['orderList'] = chooseOrderList
          chooseList.push(obj)
        }
      }
      console.log(chooseList)
      // 存小票
      this.api.rebatesubmitorders({
        'data': chooseList,
        'scheduleId': this.scheduleChoosed.id
      }).then(res => {
        console.log(res)
        if (res.data === '提交失败') {
          this.$message.error('提交失败')
          this.ifcheckbox = false
        } else {
          this.custno = res.data
          this.btnSub = true
          setTimeout(() => {
            this.$u.msg('提交成功')
            this.btnRebate = false
            this.btnCancel = false
          }, 1500)
        }
      })
    },
    // 获取token 发券操作
    async getToken() {
      this.api.rebatesendtoken().then(res => {
        this.qrCodeGeneration(res.data)
        this.rebate(this.custno, res.data)
      })
    },
    // 撤销操作
    cancelRebate() {
      this.api.updateFailStatus({
        'custno': this.custno
      }).then(res => {
        console.log(res)
        this.btnCancel = true
        this.btnRebate = true
        this.btnSub = false
        this.ifcheckbox = false
      })
    },
    // 返券动作
    async rebate(custno, token) {
      // 返券接口
      this.api.rebatecouponbytoken({
        'data': chooseList,
        'token': token,
        'custno': custno,
        'scheduleId': this.scheduleChoosed.id
      }).then(res => {
        console.log(res)
        // 关闭加载状态
        if (res.data === '返券失败') {
          this.$message.error('返券失败')
          this.cancelRebate()
        } else if (res.data === '二维码超时') {
          this.$message.error('二维码超时')
        } else if (res.data === '返券异常') {
          this.$message.error('返券异常，请联系工作人员！')
          this.cancelRebate()
        } else {
          this.dataList = []
          this.$u.msg('返券成功')
          this.btnCancel = true
          this.btnRebate = true
          this.btnSub = false
          this.ifcheckbox = false
        }
        this.qrCodeVisible = false
      })
    },
    // 清空订单
    clear() {
      this.dataList = []
    },
    // 二维码生成
    qrCodeGeneration(token) {
      this.countdown()
      const url = 'https://csms.chiconysquare.net/mp/qr/rebate?type=' + this.scheduleChoosed.type + '&token='
      // 二维码弹框显示
      this.qrCodeVisible = true
      // 生成二维码
      this.$nextTick(function() {
        document.getElementById('qrCodeUrl').innerHTML = ''
        const qrCodeUrl = new QRCode('qrCodeUrl', {
          width: 200,
          height: 200,
          text: url + token,
          colorDark: '#409EFF',
          colorLight: '#fff'
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>

.operation{
  display: flex;
  justify-content: space-around;
  padding:10px 20px;
  margin-top:10px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.operation-item{
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.operationitem-name{
  text-align: center;
  font-size: 36px;
  padding:10px 0;
  background-color: #0F8160;
  color:#fff;
}
.operationitem-order{
  padding:10px 10px;
}
.order-item{
  padding:5px 2px;
  border-bottom:2px solid #f1f1f1;
  width: 100%;
}
::v-deep .el-checkbox__label{
  vertical-align: middle;
}
.colorR{
  color:orangered;
}
.div-bottom{
  //box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border-top:2px solid #f1f1f1;
  background-color: #fff;
  padding:20px;
  position: relative;

}
::v-deep .el-dialog__header {
  text-align: center;
}

::v-deep #qrCodeUrl > img {
  margin: 0 auto;
}
</style>
